﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("rate-rule")]
    public class RateRuleController : ReceiptsBaseController<RateRule, RateRulePagingDto>
    {
        private readonly IRateRuleService _rateRuleService;
        public RateRuleController(IRateRuleService rateRuleService)
        {
            _rateRuleService = rateRuleService;
        }

        public override async Task<ResponseEntity<PagedResultDto<RateRule>>> QueryPaging([FromBody] RateRulePagingDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res?.Data?.Items?.Any() ?? false)
            {
                res.Data.Items = await this._rateRuleService.AttachWarehouse(res.Data.Items.ToArray());
            }

            return res;
        }

        //[HttpPost("add-multiple")]
        //public async Task<ResponseEntity<RateRule[]>> AddMultiple([FromBody] RateRule[] data)
        //{
        //    data.Should().NotBeNullOrEmpty();
        //    var no = await this.NoGeneratorService.GenerateReceiptNoAsync("RRL");
        //    foreach (var m in data)
        //    {
        //        this.EntityHelper.InitEntity(m);
        //        m.receiptNo = no;
        //        m.isAuditing = true;
        //    }

        //    await this.Repo.InsertManyAsync(data, autoSave: true);

        //    return new ResponseEntity<RateRule[]>().SetData(data);
        //}

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<RateRule[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<RateRule> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "RRL");
            return new ResponseEntity<RateRule[]>().SetData(res.Items);
        }

        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<RateRule[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            data = await this._rateRuleService.AttachWarehouse(data);

            return new ResponseEntity<RateRule[]>().SetData(data);
        }
    }
}
